Conversation
9899f74 to
d4c7683
Compare
Greptile SummaryThis PR significantly refactors the React compiler's impurity and ref validation system to reduce false positives and improve error actionability. Key Changes:
New Behavior:
Architecture: Confidence Score: 4/5
Important Files Changed
|
28f77b4 to
b5ec0ca
Compare
There was a problem hiding this comment.
Additional Comments (2)
-
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-mutate-ref-arg-in-render.js, line 11 (link)syntax: Typo in 'cuurrent' should be 'current'
-
compiler/packages/babel-plugin-react-compiler/src/HIR/TypeSchema.ts, line 240 (link)syntax: Missing
RenderEffectSchemain the union - should be included afterApplyEffectSchema
111 files reviewed, 5 comments
|
|
||
| export const FIXTURE_ENTRYPOINT = { | ||
| fn: Foo, | ||
| params: [{bar: 'foo'}, {ref: {cuurrent: 1}}], |
There was a problem hiding this comment.
syntax: Typo in property name: 'cuurrent' should be 'current'
| params: [{bar: 'foo'}, {ref: {cuurrent: 1}}], | |
| params: [{bar: 'foo'}, {ref: {current: 1}}], |
Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-mutate-ref-arg-in-render.expect.md
Line: 15:15
Comment:
**syntax:** Typo in property name: 'cuurrent' should be 'current'
```suggestion
params: [{bar: 'foo'}, {ref: {current: 1}}],
```
How can I resolve this? If you propose a fix, please make it concise.|
|
||
| export const FIXTURE_ENTRYPOINT = { | ||
| fn: Foo, | ||
| params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }], |
There was a problem hiding this comment.
syntax: Same typo propagated to compiled output: 'cuurrent' should be 'current'
| params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }], | |
| params: [{ bar: "foo" }, { ref: { current: 1 } }], |
Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-mutate-ref-arg-in-render.expect.md
Line: 43:43
Comment:
**syntax:** Same typo propagated to compiled output: 'cuurrent' should be 'current'
```suggestion
params: [{ bar: "foo" }, { ref: { current: 1 } }],
```
How can I resolve this? If you propose a fix, please make it concise.| * Allowed: we don't have sufficient type information to be sure that | ||
| * this accesses an impure value during render. The impurity is lost | ||
| * when passed through external function calls. |
There was a problem hiding this comment.
logic: Comment contradicts test expectation - claims this should be "Allowed" but test expects an error
| * Allowed: we don't have sufficient type information to be sure that | |
| * this accesses an impure value during render. The impurity is lost | |
| * when passed through external function calls. | |
| /** | |
| * Error: impure value accessed during render. Even though the impure value | |
| * is passed through external function calls, the compiler can still track | |
| * that it flows to the rendered output. | |
| */ |
Should this test case actually pass or is the comment outdated?
Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-impure-functions-in-render-indirect-via-mutation.expect.md
Line: 10:12
Comment:
**logic:** Comment contradicts test expectation - claims this should be "Allowed" but test expects an error
```suggestion
/**
* Error: impure value accessed during render. Even though the impure value
* is passed through external function calls, the compiler can still track
* that it flows to the rendered output.
*/
```
Should this test case actually pass or is the comment outdated?
How can I resolve this? If you propose a fix, please make it concise.Much nicer workflow for working through errors in the compiler: * Run `yarn snap -w`, oops there are are errors * Hit 'p' to select a fixture => the suggestions populate with recent failures, sorted alphabetically. No need to copy/paste the name of the fixture you want to focus on! * tab/shift-tab to pick one, hit enter to select that one * ...Focus on fixing that test... * 'p' to re-enter the picker. Snap tracks the last state of each fixture and continues to show all tests that failed on their last run, so you can easily move on to the next one. The currently selected test is highlighted, making it easy to move to the next one. * 'a' at any time to run all tests * 'd' at any time to toggle debug output on/off (while focusing on a single test)
…opment Autogenerated summaries of each of the compiler passes which allow agents to get the key ideas of a compiler pass, including key input/output invariants, without having to reprocess the file each time. In the subsequent diff this seemed to help.
Optional chaining and other value blocks within try/catch blocks were throwing an Invariant error ("Unexpected terminal in optional") instead of the expected Todo error. This caused hard failures instead of graceful bailouts.
The issue occurred because DropManualMemoization and ValidateExhaustiveDependencies ran before BuildReactiveFunction, and encountered `maybe-throw` terminals in their switch statements without a handler, falling through to the invariant case.
Fixed by adding explicit `maybe-throw` cases in both files that throw the proper Todo error with the message "Support value blocks (conditional, logical, optional chaining, etc) within a try/catch statement".
Also renamed the existing bug test to reflect it's now correctly handled:
- error.bug-invariant-unexpected-terminal-in-optional → error.todo-optional-chaining-within-try-catch
Closes #35570
Fixes a longstanding issue where we didn't support code like `useFoo(value?.bar(), value?.bar()) ?? {}` - we would attempt to construct a ReactiveFunction, recursively processing the blocks, but the inner optional `value?.bar()` wouldn't match with what the outer optional was expecting to find. It's a one-line fix!
Note: memoization in the examples is not ideal, but i've confirmed that it is not strictly related to the optional issue.
# Summary note: This implements the idea discussed in reactwg/react#389 (comment) This is a large PR that significantly changes our impurity and ref validation to address multiple issues. The goal is to reduce false positives and make the errors we do report more actionable. ## Validating Against Impure Values In Render Currently we create `Impure` effects for impure functions like `Date.now()` or `Math.random()`, and then throw if the effect is reachable during render. However, impurity is a property of the resulting value: if the value isn't accessed during render then it's okay: maybe you're console-logging the time while debugging (fine), or storing the impure value into a ref and only accessing it in an effect or event handler (totally ok). This PR updates to validate that impure values are not transitively consumed during render, building on the new effects system: rather than look at instruction types, we use effects like `Capture a -> b`, `Impure a`, and `Render b` to determine how impure values are introduced and where they flow through the program. We're intentionally conservative, and do _not_ propagate impurity through MaybeCapture effects, which is used for functions we don't have signatures for. This means that things like `identity(performance.now())` drop the impurity. This feels like a good compromise since it means we have very high confidence in the errors that we report and can always add increased strictness later as our confidence increases. An example error: ``` Error: Cannot access impure value during render Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent). error.invalid-impure-value-in-render-helper.ts:5:17 3 | const now = () => Date.now(); 4 | const render = () => { > 5 | return <div>{now()}</div>; | ^^^^^ Cannot access impure value during render 6 | }; 7 | return <div>{render()}</div>; 8 | } error.invalid-impure-value-in-render-helper.ts:3:20 1 | // @validateNoImpureFunctionsInRender 2 | function Component() { > 3 | const now = () => Date.now(); | ^^^^^^^^^^ `Date.now` is an impure function. 4 | const render = () => { 5 | return <div>{now()}</div>; 6 | }; ``` Impure values are allowed to flow into refs, meaning that we now allow `useRef(Date.now())` or `useRef(localFunctionThatReturnsMathDotRandom())` which would have errored previously. The next PR reuses this improved impurity tracking to validate ref access in render as well. ## Refs Now Treated As Impure Values in Render Reading a ref now produces an `Impure` effect, and reading refs in render is validated using the above validation against impure values in render. The error category and message is customized for refs, we're just reusing the validation implementation. This means you get consistent results for `performance.now()` as for `ref.current`. A nice consistency win. ## Simplified writing-ref validation Now that _reading_ a ref in render is validated using the impure values infra, I also dramatically simplified ValidateNoRefAccessInRender to focus solely on validation against _writing_ refs during render. It was harder to use the new effects infra for this since we intentionally do not record ref mutations as a `Mutate` effect. So for now, the pass switches on InstructionValue variants. We continue to support the `if (ref.current == null) { ref.current = <init> }` pattern and reasonable variants of it. We're conservative about what we consider to be a write of a ref - `foo(ref)` now assumes you're not mutating rather than the inverse. # Takeaways * Impure-values-in-render logic is more conservative about what it considers an error (ie to users it appears more persmissive). We follow clearly identifiable (and if we wanted traceable/explainable) paths from impure sources through to where they are rendered. We allow many more cases than before, notably `x = foo(ref)` optimistically assumes you don't read the ref. Concretely, this follows from not tracking impure values across MaybeCapture effects. * No-writing-refs-in-render is also more conservative about what it counts as a write, appearing to users as allowing more cases. We look for very direct evidence of writing to refs, ie `ref.current = <value>` or `ref.current.property = <value>`, and allow potential writes through eg `writeToRef(ref, value)`.
There was a problem hiding this comment.
Additional Comments (1)
-
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-mutate-ref-arg-in-render.js, line 10 (link)syntax: Typo in fixture data:
cuurrentshould becurrent
215 files reviewed, 3 comments
| /** | ||
| * Allowed: we don't have sufficient type information to be sure that | ||
| * this accesses an impure value during render. The impurity is lost | ||
| * when passed through external function calls. | ||
| */ |
There was a problem hiding this comment.
style: Comment is misleading - claims "Allowed" but test expects an error
The comment states this case is allowed because "impurity is lost when passed through external function calls", but the test fixture expects an error. The implementation correctly tracks impurity through the arrayPush mutation and renders it, so it should error. Update comment to match actual behavior.
| /** | |
| * Allowed: we don't have sufficient type information to be sure that | |
| * this accesses an impure value during render. The impurity is lost | |
| * when passed through external function calls. | |
| */ | |
| /** | |
| * The impure value flows through arrayPush into the array and is rendered. | |
| * Even though arrayPush is an external function, the impurity is tracked | |
| * through the mutation and reaches the render site. | |
| */ |
Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-impure-functions-in-render-indirect-via-mutation.js
Line: 5:9
Comment:
**style:** Comment is misleading - claims "Allowed" but test expects an error
The comment states this case is allowed because "impurity is lost when passed through external function calls", but the test fixture expects an error. The implementation correctly tracks impurity through the `arrayPush` mutation and renders it, so it should error. Update comment to match actual behavior.
```suggestion
/**
* The impure value flows through arrayPush into the array and is rendered.
* Even though arrayPush is an external function, the impurity is tracked
* through the mutation and reaches the render site.
*/
```
How can I resolve this? If you propose a fix, please make it concise.| if ( | ||
| sourceEffect == null && | ||
| (effect.kind === 'Assign' || effect.kind === 'Capture') && | ||
| !impure.has(effect.from.identifier.id) && | ||
| !rendered.has(effect.from.identifier.id) && | ||
| !isUseRefType(effect.from.identifier) && | ||
| isMutable({id}, effect.into) | ||
| ) { | ||
| const destinationEffect = impure.get(effect.into.identifier.id); | ||
| if (destinationEffect != null) { | ||
| impure.set(effect.from.identifier.id, destinationEffect); | ||
| hasChanges = true; | ||
| } | ||
| } |
There was a problem hiding this comment.
style: Bidirectional impurity propagation handles mutations like arrayPush(array, impureValue) - when an impure value is captured into a mutable destination, the destination becomes impure and can propagate forward to render sites
Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoImpureValuesInRender.ts
Line: 100:113
Comment:
**style:** Bidirectional impurity propagation handles mutations like `arrayPush(array, impureValue)` - when an impure value is captured into a mutable destination, the destination becomes impure and can propagate forward to render sites
How can I resolve this? If you propose a fix, please make it concise.
Mirror of facebook/react#35298
Original author: josephsavona
Summary
note: This implements the idea discussed in https://github.com/reactwg/react/discussions/389#discussioncomment-14252280
This is a large PR that significantly changes our impurity and ref validation to address multiple issues. The goal is to reduce false positives and make the errors we do report more actionable.
Validating Against Impure Values In Render
Currently we create
Impureeffects for impure functions likeDate.now()orMath.random(), and then throw if the effect is reachable during render. However, impurity is a property of the resulting value: if the value isn't accessed during render then it's okay: maybe you're console-logging the time while debugging (fine), or storing the impure value into a ref and only accessing it in an effect or event handler (totally ok).This PR updates to validate that impure values are not transitively consumed during render, building on the new effects system: rather than look at instruction types, we use effects like
Capture a -> b,Impure a, andRender bto determine how impure values are introduced and where they flow through the program. We're intentionally conservative, and do not propagate impurity through MaybeCapture effects, which is used for functions we don't have signatures for. This means that things likeidentity(performance.now())drop the impurity. This feels like a good compromise since it means we have very high confidence in the errors that we report and can always add increased strictness later as our confidence increases.An example error:
Impure values are allowed to flow into refs, meaning that we now allow
useRef(Date.now())oruseRef(localFunctionThatReturnsMathDotRandom())which would have errored previously. The next PR reuses this improved impurity tracking to validate ref access in render as well.Refs Now Treated As Impure Values in Render
Reading a ref now produces an
Impureeffect, and reading refs in render is validated using the above validation against impure values in render. The error category and message is customized for refs, we're just reusing the validation implementation. This means you get consistent results forperformance.now()as forref.current. A nice consistency win.Simplified writing-ref validation
Now that reading a ref in render is validated using the impure values infra, I also dramatically simplified ValidateNoRefAccessInRender to focus solely on validation against writing refs during render. It was harder to use the new effects infra for this since we intentionally do not record ref mutations as a
Mutateeffect. So for now, the pass switches on InstructionValue variants. We continue to support theif (ref.current == null) { ref.current = <init> }pattern and reasonable variants of it. We're conservative about what we consider to be a write of a ref -foo(ref)now assumes you're not mutating rather than the inverse.Takeaways
x = foo(ref)optimistically assumes you don't read the ref. Concretely, this follows from not tracking impure values across MaybeCapture effects.ref.current = <value>orref.current.property = <value>, and allow potential writes through egwriteToRef(ref, value).Stack created with Sapling. Best reviewed with ReviewStack.